package com.zy.controller;

import com.github.pagehelper.PageInfo;
import com.zy.controller.vo.ItemVO;
import com.zy.dataobject.ItemExample;
import com.zy.error.BusinessException;
import com.zy.response.CommonReturnType;
import com.zy.service.IItemService;
import com.zy.service.model.ItemModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by zhaoyang on 2019/6/24.
 */
@Controller("itemController")
@RequestMapping("/item")
@CrossOrigin(
        allowedHeaders = "*",allowCredentials = "true"
)
public class ItemController extends BaseController {

    @Autowired
    private IItemService itemService;

    @RequestMapping("/detail")
    @ResponseBody
    public CommonReturnType getItem(@RequestParam("id")Integer id) throws BusinessException {
        ItemModel itemModel = itemService.getItemById(id);
        ItemVO itemVO = convertToItemVO(itemModel);

        CommonReturnType returnType = CommonReturnType.createSuccess(itemVO);

        return returnType;
    }

    @RequestMapping("/list")
    @ResponseBody
    public CommonReturnType itemList() {
        ItemExample itemExample = new ItemExample();
        itemExample.createCriteria().andIdEqualTo(2);
        List<ItemModel> itemModels = itemService.listItem(itemExample);
        PageInfo<ItemModel> modelPageInfo = new PageInfo<>(itemModels);
        CommonReturnType returnType = CommonReturnType.createSuccess(modelPageInfo);
        return returnType;
    }

    private ItemVO convertToItemVO(ItemModel itemModel) {
        if (itemModel == null) {
            return null;
        }
        ItemVO itemVO = new ItemVO();
        BeanUtils.copyProperties(itemModel,itemVO);
        return itemVO;
    }

}
